// Copyright 2013 Beego Samples authors
//
// Licensed under the Apache License, Version 2.0 (the "License"): you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.

package controllers

import (
	"bufio"
	"context"
	"encoding/base64"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/beego/samples/WebIM/models"
	"encoding/json"
	"github.com/docker/docker/api/types"
	"github.com/docker/docker/client"
	"io"
	"os"
	"strconv"
)

// LongPollingController handles long polling requests.
type LongPollingController struct {
	baseController
}



// Join method handles GET requests for LongPollingController.
func (this *LongPollingController) Join() {
	// Safe check.
	uname:="test"

	// Join chat room.
	Join(uname, nil)

	this.TplName = "install/baseService.html"
	this.Data["IsLongPolling"] = true
	this.Data["UserName"] = uname
}



func  (this *LongPollingController) GetClient() (*client.Client,context.Context){
	ctx := context.Background()
	cli, err := client.NewClientWithOpts(client.WithVersion("1.38"))
	if err != nil {
		panic(err)
	}
	config := types.AuthConfig{
		Username: "renjie59420",
		Password: "rj123456",
		ServerAddress: "registry.cn-shenzhen.aliyuncs.com",
	}
	response, err := cli.RegistryLogin(ctx, config)
	//expected := "Error response from daemon: Get https://registry-1.docker.io/v2/: unauthorized: incorrect username or password"
	if err != nil {
		panic(err)
	}
	beego.Debug(response)
	return cli,context.Background()
}


// Post method handles receive messages requests for LongPollingController.
func (this *LongPollingController) Post() {
	//this.TplName = "install/longpolling.html"
	//uname := this.GetString("uname")
	//content := this.GetString("content")

	cli, ctx := this.GetClient()
	username :="renjie59420"
	password := "rj123456"
	imageName:="registry.cn-shenzhen.aliyuncs.com/uniappadmin/uniappadmin"
	jsonBytes, _ := json.Marshal(map[string]string{
		"username":  username,"password": password})

	opts := types.ImagePullOptions{
		RegistryAuth: base64.StdEncoding.EncodeToString(jsonBytes)}

	reader, err := cli.ImagePull(ctx, imageName, opts)
	if err != nil {
		panic(err)
	}




	//buf := new(bytes.Buffer)

	var i=0
	//for {

		done := make(chan struct{})

		scanner := bufio.NewScanner(reader)
		go func() {
			for scanner.Scan() {
				i++

				publish <- newEvent(models.EVENT_MESSAGE,  strconv.Itoa(i), scanner.Text())
				fmt.Printf("%s\n", scanner.Text())
			}

			done <- struct{}{}
		}()

		<-done
	io.Copy(os.Stdout, reader)

	//	time.Sleep(time.Duration(1)*time.Second)
		//buf.ReadFrom(os.Stdout)
		//newStr := buf.String()
		//beego.Debug(newStr+"AAA")
		//fmt.Printf(newStr+"BBB")

//	}

}

type ImageJson struct {

	status string `json:"status"`
	id string `json:"id"`
}
// Fetch method handles fetch archives requests for LongPollingController.
func (this *LongPollingController) Fetch() {
	lastReceived, err := this.GetInt("lastReceived")
	if err != nil {
		return
	}

	events := models.GetEvents(int(lastReceived))
	if len(events) > 0 {
		this.Data["json"] = events
		this.ServeJSON()
		return
	}

	// Wait for new message(s).
	ch := make(chan bool)
	waitingList.PushBack(ch)
	<-ch

	this.Data["json"] = models.GetEvents(int(lastReceived))
	this.ServeJSON()
}
